package com.project.common;


import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver;

import com.dtyunxi.rest.RestCode;
import com.dtyunxi.rest.RestResponse;
import com.dtyunxi.util.JacksonUtil;
import com.fasterxml.jackson.core.JsonProcessingException;


public class GlobalExceptionHandler extends DefaultHandlerExceptionResolver {

	private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

	@Override
	public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
			Exception ex) {

		boolean ajax = this.isAjax(request, handler);

		if (ajax) {
			return this.ajaxResult(ex, response);
		} else {
			request.setAttribute("exception", ex.getMessage());
			return this.result(ex, response);
		}

	}

	private ModelAndView result(Exception ex, HttpServletResponse response) {
		try {
			response.sendError(500);
		} catch (IOException e) {
			logger.error(e.getMessage(), e);
		}
		logger.error("系统出错,cause:{}", ex.getMessage(), ex);
		return new ModelAndView();
	}

	private ModelAndView ajaxResult(Exception ex, HttpServletResponse response) {

		logger.error("系统出错,cause:{}", ex.getMessage(), ex);
		return processException(response, RestCode.RESULT_SYSTEM_ERROR, "系统错误,请稍后再试！");
	}

	/**
	 * 返回json格式
	 * 
	 * @param response
	 * @param code
	 * @param message
	 * @return ModelAndView
	 */
	private ModelAndView processException(HttpServletResponse response, int code, String message) {
		RestResponse br = new RestResponse(code, message, null);
		response.setContentType("application/json;charset=UTF-8");
		PrintWriter out = null;
		try {
			out = response.getWriter();
			out.write(JacksonUtil.toJson(br));
		} catch (JsonProcessingException e) {
			logger.error(e.getMessage(), e);
		} catch (IOException e) {
			logger.error(e.getMessage(), e);
		}
		return new ModelAndView();
	}

	/**
	 * 判断是否为ajax请求.没有找到什么好办法 这里只是简单的认为请求来自jquery的ajax 或者相应方法标注是responseBody
	 * 
	 * @param request
	 * @return boolean
	 */
	private boolean isAjax(HttpServletRequest request, Object handler) {

		if (null != handler && handler instanceof HandlerMethod) {
			HandlerMethod method = (HandlerMethod) handler;
			if (null != method.getBeanType().getAnnotation(RestController.class)) {
				return true;
			}
			if (method.getMethodAnnotation(ResponseBody.class) != null) {
				return true;
			}
		}
		String head = request.getHeader("X-Requested-With");

		if (StringUtils.isNotBlank(head)) {
			return true;
		}
		return false;
	}

}
